<template>
  <view class="login-container">
    <image class="logo" src="/static/lanqiao-logo.svg"></image>
    <input v-model="phone" type="number" placeholder="请输入手机号" class="input" />
    <input v-model="password" type="password" placeholder="请输入密码" class="input" />
    <button class="login-btn" @click="login">登录</button>
    <view class="register-link" @click="toRegister">立即注册</view>
  </view>
</template>

<script>
import config from "@/config.js";

export default {
  data() {
    return {
      phone: '',
      password: ''
    };
  },
  mounted() {
    const token = uni.getStorageSync('token');
    if (token) {
      uni.switchTab({ url: '/pages/me/me' });
    }
  },
  methods: {
    validatePhone() {
      return /^1\d{10}$/.test(this.phone);
    },
    toRegister() {
      uni.navigateTo({ url: '/pages/register/register' });
    },
    async login() {
      if (!this.phone) {
        return uni.showToast({ title: '请输入手机号', icon: 'none' });
      }
      if (!this.validatePhone()) {
        return uni.showToast({ title: '请输入正确的11位手机号', icon: 'none' });
      }
      if (!this.password) {
        return uni.showToast({ title: '请输入密码', icon: 'none' });
      }

      try {
        // 1. 验证用户是否存在
        const response = await uni.request({
          url: `${config.api_host}users?username=${this.phone}&password=${this.password}`,
          method: 'GET'
        });
        
        if (response.data.length === 0) {
          throw new Error('用户名或密码错误');
        }
        
        const user = response.data[0];
        
        // 2. 存储用户信息和token
        uni.setStorageSync('token', 'user-token-' + user.id); // 简单模拟token
        uni.setStorageSync('userId', user.id);
        uni.setStorageSync('userInfo', {
          id: user.id,
          username: user.username,
          name: user.name
        });

        uni.showToast({ title: '登录成功', icon:'success' });
        setTimeout(() => {
          uni.switchTab({ url: '/pages/me/me' });
        }, 1500);
      } catch (error) {
        console.error('登录失败:', error);
        uni.showToast({ 
          title: error.message || '登录失败，请重试', 
          icon: 'none' 
        });
      }
    }
  }
};
</script>

<style scoped>
.login-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.logo {
  width: 120px;
  height: 120px;
  margin-bottom: 30px;
}

.input {
  width: 300px;
  height: 40px;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0 10px;
  margin-bottom: 20px;
}

.login-btn {
  width: 300px;
  height: 45px;
  background-color: #007AFF;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
}

.register-link {
  color: #999;
  margin-top: 15px;
  cursor: pointer;
}
</style>